package com.example.tianling.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tianling.common.utils.RedisUtils;
import com.example.tianling.dao.UserInfoMapper;
import com.example.tianling.entity.UserInfoEntity;
import com.example.tianling.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfoEntity> implements UserInfoService {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public UserInfoEntity getUserInfo(Integer userId) {

        UserInfoEntity userInfo = redisUtils.get("userInfo_"+userId, UserInfoEntity.class);
        if (userInfo == null) {
            userInfo = this.lambdaQuery()
                    .eq(UserInfoEntity::getUserId, userId)
                    .last("LIMIT 1")
                    .one();
            redisUtils.set("userInfo_"+userId, userInfo, 24*60*60);
        }
        return userInfo;
    }

    @Override
    public void updateUserExperience(Integer userId, Integer experience) {
        UserInfoEntity userInfo = getUserInfo(userId);

        int newExp = userInfo.getExperience() + experience;
        userInfo.setExperience(newExp);

        List<Integer> levelList = Arrays.asList(0, 40, 120, 280, 600);
        int level = userInfo.getLevel();
        if (newExp > levelList.get(level + 1)) {
            userInfo.setLevel(level+1);
            userInfo.setIsReward(1);
        }

        redisUtils.set("userInfo_"+userId, userInfo, 24*60*60);
        baseMapper.updateById(userInfo);
    }

    @Override
    public UserInfoEntity getReward(Integer userId) {
        UserInfoEntity userInfo = getUserInfo(userId);
        if (userInfo.getIsReward() == 1) {
            userInfo.setIsReward(0);
            // 根据等级来添加
            userInfo.setTrainTicket(userInfo.getTrainTicket() + 10);
            userInfo.setAiTicket(userInfo.getAiTicket() + 10);
        }
        redisUtils.set("userInfo_"+userId, userInfo, 24*60*60);
        baseMapper.updateById(userInfo);
        return userInfo;
    }
}
